import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { getSalaryList, getSalaryDetail, createSalary, updateSalary, deleteSalary, getMySalary, calculateSalary } from '../api/salary'

// 异步获取薪资列表
export const fetchSalaries = createAsyncThunk(
  'salary/fetchSalaries',
  async (params, { rejectWithValue }) => {
    try {
      const response = await getSalaryList(params)
      return response
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取薪资列表失败' })
    }
  }
)

// 异步获取个人薪资记录
export const fetchMySalary = createAsyncThunk(
  'salary/fetchMySalary',
  async (params, { rejectWithValue }) => {
    try {
      const response = await getMySalary(params)
      return response
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取个人薪资记录失败' })
    }
  }
)

// 异步获取薪资详情
export const fetchSalaryDetail = createAsyncThunk(
  'salary/fetchSalaryDetail',
  async (id, { rejectWithValue }) => {
    try {
      const response = await getSalaryDetail(id)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取薪资详情失败' })
    }
  }
)

// 异步计算薪资
export const computeSalary = createAsyncThunk(
  'salary/computeSalary',
  async (params, { rejectWithValue }) => {
    try {
      const response = await calculateSalary(params)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '计算薪资失败' })
    }
  }
)

// 异步创建薪资记录
export const addSalary = createAsyncThunk(
  'salary/addSalary',
  async (salaryData, { rejectWithValue }) => {
    try {
      const response = await createSalary(salaryData)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '添加薪资记录失败' })
    }
  }
)

// 异步更新薪资记录
export const editSalary = createAsyncThunk(
  'salary/editSalary',
  async ({ id, data }, { rejectWithValue }) => {
    try {
      const response = await updateSalary(id, data)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '更新薪资记录失败' })
    }
  }
)

// 异步删除薪资记录
export const removeSalary = createAsyncThunk(
  'salary/removeSalary',
  async (id, { rejectWithValue }) => {
    try {
      await deleteSalary(id)
      return id
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '删除薪资记录失败' })
    }
  }
)

const initialState = {
  salaries: [],
  mySalaries: [],
  currentSalary: null,
  calculatedSalary: null,
  pagination: {
    current: 1,
    pageSize: 10,
    total: 0
  },
  myPagination: {
    current: 1,
    pageSize: 10,
    total: 0
  },
  loading: false,
  error: null,
  statistics: {
    totalAmount: 0,
    averageSalary: 0,
    highestSalary: 0,
    lowestSalary: 0
  }
}

const salarySlice = createSlice({
  name: 'salary',
  initialState,
  reducers: {
    clearError: (state) => {
      state.error = null
    },
    setCurrentPage: (state, action) => {
      state.pagination.current = action.payload
    },
    setPageSize: (state, action) => {
      state.pagination.pageSize = action.payload
    },
    setMyCurrentPage: (state, action) => {
      state.myPagination.current = action.payload
    },
    setMyPageSize: (state, action) => {
      state.myPagination.pageSize = action.payload
    },
    clearCurrentSalary: (state) => {
      state.currentSalary = null
    },
    clearCalculatedSalary: (state) => {
      state.calculatedSalary = null
    }
  },
  extraReducers: (builder) => {
    builder
      // 获取薪资列表
      .addCase(fetchSalaries.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchSalaries.fulfilled, (state, action) => {
        state.loading = false
        state.salaries = action.payload.data || []
        state.pagination.total = action.payload.total || 0
        // 更新统计数据
        if (action.payload.statistics) {
          state.statistics = action.payload.statistics
        }
      })
      .addCase(fetchSalaries.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取薪资列表失败'
      })
      // 获取个人薪资记录
      .addCase(fetchMySalary.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchMySalary.fulfilled, (state, action) => {
        state.loading = false
        state.mySalaries = action.payload.data || []
        state.myPagination.total = action.payload.total || 0
      })
      .addCase(fetchMySalary.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取个人薪资记录失败'
      })
      // 获取薪资详情
      .addCase(fetchSalaryDetail.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchSalaryDetail.fulfilled, (state, action) => {
        state.loading = false
        state.currentSalary = action.payload
      })
      .addCase(fetchSalaryDetail.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取薪资详情失败'
      })
      // 计算薪资
      .addCase(computeSalary.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(computeSalary.fulfilled, (state, action) => {
        state.loading = false
        state.calculatedSalary = action.payload
      })
      .addCase(computeSalary.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '计算薪资失败'
      })
      // 添加薪资记录
      .addCase(addSalary.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(addSalary.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(addSalary.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '添加薪资记录失败'
      })
      // 更新薪资记录
      .addCase(editSalary.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(editSalary.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(editSalary.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '更新薪资记录失败'
      })
      // 删除薪资记录
      .addCase(removeSalary.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(removeSalary.fulfilled, (state, action) => {
        state.loading = false
        state.salaries = state.salaries.filter(salary => salary.id !== action.payload)
      })
      .addCase(removeSalary.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '删除薪资记录失败'
      })
  }
})

export const { 
  clearError, 
  setCurrentPage, 
  setPageSize, 
  setMyCurrentPage, 
  setMyPageSize, 
  clearCurrentSalary,
  clearCalculatedSalary 
} = salarySlice.actions

export default salarySlice.reducer